﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;

public partial class User_QuanLyBanner : System.Web.UI.Page
{
    security baomat = new security();
    string username;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            HttpCookie _user = Request.Cookies["userinfo"];
            if (Request.Cookies["userinfo"] != null)
            {
                if (_user["username"] != null)
                {
                    username = _user["username"];
                    bannerList();
                    if (Page.RouteData.Route != null)
                    {
                        string position = Page.RouteData.GetRequiredString("position").ToUpper();
                        ddlBannerPosition.Items.FindByValue(position).Selected = true;
                        imageSize(position);
                    }
                }
                else
                {
                    Response.RedirectToRoute("Index");
                }
            }
        }
        catch (Exception)
        {
            Response.RedirectToRoute("Error");
        }
    }
    private void pointPackage(Up1VNDataContext dc)
    {
        var point = (from p in dc.PointBackages select p).ToList();
        ddlPointPackage.DataSource = point;
        ddlPointPackage.DataTextField = "PointBackage_Point";
        ddlPointPackage.DataValueField = "PointBackage_Id";
        ddlPointPackage.DataBind();
    }
    public string showDateTime(string input)
    {
        if (input != "")
            return baomat.convertTimeTo_dMy(input);
        else
            return "";
    }
    public string activeAdv(string input)
    {
        string output=String.Empty;
        switch (int.Parse(input))
        {
            case 3: output = "Đã kích hoạt";
                break;
            case 1: output = "Chưa kích hoạt";
                break;
        }
        return output;
    }
    private void bannerList()
    {
        try
        {
            using (Up1VNDataContext dc = new Up1VNDataContext())
            {
                pointPackage(dc);
                var quangcao = from u in dc.Users
                               join adv in dc.UsersAdvs on u.Users_Id equals adv.Users_Id
                               where u.Users_Name == username
                               select adv;
                if (quangcao.Count() > 0)
                {
                    rptBanner.DataSource = quangcao.ToList();
                    rptBanner.DataBind();
                }
            }
        }
        catch (Exception)
        {
            Response.RedirectToRoute("Error");
        }
    }
    protected void btnRegis_Adv_Click(object sender, EventArgs e)
    {
        try
        {
            imageSize(ddlBannerPosition.SelectedValue.ToString());
            if (strFileUpload.HasFile)
            {
                if (IsGraphic(strFileUpload.FileName))
                {
                    string fullPath = Server.MapPath(@"images/banners");
                    //if (!Directory.Exists(fullPath))
                    //{
                    //    Directory.CreateDirectory(fullPath);
                    //    DirectoryInfo di = Directory.CreateDirectory(fullPath);
                    //}
                    //strFileUpload.SaveAs(fullPath + "/" + strFileUpload.FileName);
                    //System.Drawing.Image original = System.Drawing.Image.FromFile(fullPath + "/" + strFileUpload.FileName);
                    //if (original.Width > ImagesSize.Width || original.Height > ImagesSize.Height)
                    //{
                    //    System.Drawing.Image imgResize = ImageProgress.ImagesResize.ResizeImage(original, ImagesSize.Width, ImagesSize.Height);
                    //    imgResize.Save(fullPath + "/" + strFileUpload.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    //}
                    int thumbWidth = ImagesSize.Width;
                    int thumbHeight = ImagesSize.Height;
                    String UploadedFile = strFileUpload.PostedFile.FileName;
                    int ExtractPos = UploadedFile.LastIndexOf("\\") + 1;
                    String UploadedFileName = UploadedFile.Substring(ExtractPos, UploadedFile.Length - ExtractPos);
                    string filename =DateTime.Now.Day+"_"+DateTime.Now.Hour+"_"+DateTime.Now.Minute+"_"+DateTime.Now.Second+"_"+ strFileUpload.FileName;
                    strFileUpload.PostedFile.SaveAs(fullPath + "\\" + filename);
                    String imageUrl = UploadedFileName;
                    System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(fullPath + "\\" + filename);
                    System.Drawing.Image.GetThumbnailImageAbort dummyCallBack= new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                    System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(thumbWidth, thumbHeight,dummyCallBack, IntPtr.Zero);

                    //We need to create a unique filename for each generated image
                    DateTime MyDate = DateTime.Now;

                    String MyString = MyDate.ToString("ddMMyyhhmmss") + ".Jpeg";

                    //Save the thumbnail in PNG format. 
                    //You may change it to a diff format with the ImageFormat property
                    thumbNailImg.Save(fullPath + "\\" + filename, ImageFormat.Jpeg);
                    thumbNailImg.Dispose();
                    //System.Drawing.Image oImg = System.Drawing.Image.FromStream(strFileUpload.PostedFile.InputStream);
                    //System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);

                    //Graphics oGraphic = Graphics.FromImage(oThumbNail);
                    //oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                    //oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                    //oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    //Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                    //oGraphic.DrawImage(oImg, oRectangle);

                    //oThumbNail.Save(fullPath + "/" + filename);
                    //oImg.Dispose();
                    using (Up1VNDataContext dc = new Up1VNDataContext())
                    {
                        var checkUserAdv = dc.Users.Single(u=>u.Users_Name==username);
                        UsersAdv adv = new UsersAdv();
                        adv.Users_Id = checkUserAdv.Users_Id;
                        adv.UsersAdv_PicturePath = filename;
                        if (txtStartShow.Text != "")
                            adv.UsersAdv_FromDate = Convert.ToDateTime(baomat.convertTimeTo_Mdy(txtStartShow.Text));
                        adv.UsersAdv_Status = BannerStatus.waiting;
                        adv.UsersAdv_Location = ddlBannerPosition.SelectedValue;
                        adv.PointBackage_Id =long.Parse(ddlPointPackage.SelectedValue.ToString());
                        dc.UsersAdvs.InsertOnSubmit(adv);
                        dc.SubmitChanges();
                        dc.Dispose();
                    }
                    //strFileUpload.SaveAs(fullPath + "/" + imgResize);
                    bannerList();
                }
                else
                {
                }
            }
        }
        catch (Exception)
        {
        }
    }
    public bool ThumbnailCallback()
    {
        return false;
    }
    protected void btnCancel_adv_Click(object sender, EventArgs e)
    {
        try
        {
        }
        catch (Exception)
        {
        }
    }
    public void ResizeImagePercent(double scaleFactor, Stream fromStream, Stream toStream)
    {
        var image = System.Drawing.Image.FromStream(fromStream);
        var newWidth = (int)(image.Width * scaleFactor);
        var newHeight = (int)(image.Height * scaleFactor);
        var thumbnailBitmap = new Bitmap(newWidth, newHeight);

        var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
        thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
        thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
        thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

        var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
        thumbnailGraph.DrawImage(image, imageRectangle);
        MemoryStream mms = new MemoryStream();
        thumbnailBitmap.Save(toStream, image.RawFormat);

        thumbnailGraph.Dispose();
        thumbnailBitmap.Dispose();
        image.Dispose();
    }
    public bool IsGraphic(string Path)
    {
        Regex r = new Regex(@"\.gif$|\.jpg$|\.jpeg$|\.png$", RegexOptions.IgnoreCase);
        if (r.IsMatch(Path))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private void imageSize(string position)
    {
        switch (position.ToUpper())
        {
            case "TOP":
            case "FOOTER":
                lblsizebanner.Text = "640x60";
                ImagesSize.Width = 640;
                ImagesSize.Height = 60;
                break;
            case "CENTER":
                lblsizebanner.Text = "270x60";
                ImagesSize.Width = 270;
                ImagesSize.Height = 60;
                break;
        }
    }
}